package com.six.backend.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.six.backend.config.QiNiuCloudProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * @Author: skyler
 * @Date: 2021/11/20 9:24
 */
@Slf4j
public class QiNiuUtils {
    /**
     * 实现上传文件至七牛云
     * @param qiNiuCloudProperties 七牛云配置类
     * @param file 上传文件对象
     * @return 七牛云存储的路径
     *
     */
    public static String upload(QiNiuCloudProperties qiNiuCloudProperties, MultipartFile file)  {
        // 构造一个带指定 Region 对象的配置类
        Configuration configuration = new Configuration(Region.huanan());
        // 七牛文件上传管理器
        UploadManager uploadManager = new UploadManager(configuration);
        // 获取Auth对象
        Auth auth = Auth.create(qiNiuCloudProperties.getAccessKey(),qiNiuCloudProperties.getSecretKey());
        // 生成上传凭证，然后准备上传
        String uploadToken = auth.uploadToken(qiNiuCloudProperties.getBucket());
        log.debug("生成的上传凭证是: "+uploadToken);
        try {
            // 上传文件   默认不指定key的情况下，以文件内容的hash值作为文件名
            Response response = uploadManager.put(file.getInputStream(),null, uploadToken, null, null);
            // 解析上传成功的结果
            DefaultPutRet defaultPutRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            // 返回文件名
            return  defaultPutRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return "上传失败";
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }

    }

    /**
     * 删除七牛云存储的文件
     * @param qiNiuCloudProperties 进入七牛云仓库的相关参数
     * @param key 文件名
     * @return 文件删除的状态
     */
    public static String delete(QiNiuCloudProperties qiNiuCloudProperties,String key) {
        Configuration cfg = new Configuration(Region.huanan());
//...其他参数参考类注释
        String bucket = qiNiuCloudProperties.getBucket();
        Auth auth = Auth.create(qiNiuCloudProperties.getAccessKey(), qiNiuCloudProperties.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
            return "true";
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            return "false";
        }
    }

    public static String localUpload(QiNiuCloudProperties qiNiuCloudProperties,String localFilePath,String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
    //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
    //...生成上传凭证，然后准备上传
        String bucket = qiNiuCloudProperties.getBucket();
    //如果是Windows情况下，格式是 D:\\qiniu\\test.png
//        String localFilePath = "/home/qiniu/test.png";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
        Auth auth = Auth.create(qiNiuCloudProperties.getAccessKey(), qiNiuCloudProperties.getSecretKey());
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            return "false";
        }
    }


    public static String localChunkUpload(String realPath, String name) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        cfg.resumableUploadMaxConcurrentTaskCount = 3;  // 设置分片上传并发，1：采用同步上传；大于1：采用并发上传
        //...其他参数参考类注释
        //...生成上传凭证，然后准备上传
        String accessKey = EncryptUtil.decrypt("9fLSBPOd5vW5LU1x/1aK6PCHAljXDloY9bg+9pc2U63ur179FznHrI9MQRJSGfoEM+x/IQWpAoM=");
        String secretKey = EncryptUtil.decrypt("LDOS5Sazj1nQuedFo/OD8CZ99mFwWY13ZlYVjJJ5Y0ndtuUhS88pYQquJKJOlJxdAkTukFYwYXs=");
        String bucket = "skyler-store";
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = realPath;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = name;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString();
        //设置断点续传文件进度保存目录
        FileRecorder fileRecorder = null;
        try {
            fileRecorder = new FileRecorder(localTempDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                return r.bodyString();
            } catch (QiniuException ex2) {
                //ignore
                ex2.printStackTrace();
            }
        }
        return "false";
    }
}
